﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        #region Private Members
        private readonly string xsdFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "VehiclesRepairs.xsd");
        private readonly string xmlFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "VehiclesRepairs.xml");
        private DataSet ds;
        #endregion

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            PopulateDataSet();
            // bind sources
            dgVehicles.DataSource = ds;
            dgVehicles.DataMember = "Vehicles";
            dgRepairs.DataSource = ds;
            dgRepairs.DataMember = "Vehicles.vehicles_repairs";
        }

        void CreateSchema()
        {
            ds = new DataSet("VehiclesRepairs");
            var vehicles = ds.Tables.Add("Vehicles");
            vehicles.Columns.Add("VIN", typeof(string));
            vehicles.Columns.Add("Make", typeof(string));
            vehicles.Columns.Add("Model", typeof(string));
            vehicles.Columns.Add("Year", typeof(int));
            vehicles.PrimaryKey = new DataColumn[] { vehicles.Columns["VIN"] };

            var repairs = ds.Tables.Add("Repairs");
            var pk = repairs.Columns.Add("ID", typeof(int));
            pk.AutoIncrement = true;
            pk.AutoIncrementSeed = -1;
            pk.AutoIncrementStep = -1;
            repairs.Columns.Add("VIN", typeof(string));
            repairs.Columns.Add("Descriptions", typeof(string));
            repairs.Columns.Add("Cost", typeof(decimal));
            repairs.PrimaryKey = new DataColumn[] { repairs.Columns["ID"] };

            ds.Relations.Add("vehicles_repairs", vehicles.Columns["VIN"], repairs.Columns["VIN"]);
            ds.WriteXmlSchema(xsdFile);
        }

        void PopulateDataSet()
        {
            // validate schema file exists
            if (File.Exists(xsdFile))
            {
                // read schema
                ds = new DataSet();
                ds.ReadXmlSchema(xsdFile);
            }
            else
            {
                // create schema
                CreateSchema();
            }
            // validate xml data exists
            if (File.Exists(xmlFile))
            {
                // read xml data
                ds.ReadXml(xmlFile, XmlReadMode.IgnoreSchema);
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // save data on xml format
            ds.WriteXml(xmlFile, XmlWriteMode.DiffGram);
        }
    }
}
